package com.sys.Utils;

import com.sys.annotation.EcexlFiled;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

public class ExcelUtil {

    /**
     * 导出excel工具类
     *
     * @param title 工作表名称
     * @param heads 表头名称
     * @param list  需要导出的数据集合
     */
    public static HSSFWorkbook outPutExce(String title, String[] heads, List list,Class clazz) throws Exception {

        if (CollectionUtils.isEmpty(list)) {
            throw new NullPointerException("导出数据为空");
        }
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(!StringUtils.isEmpty(title) ? title : "sheet");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        HSSFCell cell;
        if (heads != null && heads.length > 0) {
            for (int i = 0; i < heads.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(heads[i]);
                cell.setCellStyle(style);
            }
        }
        //获取所有字段
        List<Field> fieldsList = getAllFields(clazz);

        List<ObjectFild> fieldList = new ArrayList<ObjectFild>();
        if (fieldsList != null && fieldsList.size() > 0) {
            for (Field f : fieldsList) {
                EcexlFiled annotation = f.getAnnotation(EcexlFiled.class);
                if (annotation != null) {
                    ObjectFild field = new ObjectFild();
                    field.order = annotation.value();
                    field.fieldName = f.getName();
                    field.field = f;
                    fieldList.add(field);
                }
            }
        }
        //按照字段排序
        Collections.sort(fieldList, new Comparator<ObjectFild>() {
            @Override
            public int compare(ObjectFild o1, ObjectFild o2) {
                if (o1.order > o2.order) return 1;
                if (o1.order < o2.order) return -1;
                return 0;
            }
        });
        int j = 1;
        for (Object aList : list) {
            row = sheet.createRow(j);
            if (!CollectionUtils.isEmpty(fieldList)) {
                Class<?> aClass1 = aList.getClass();
                for (int k = 0; k < fieldList.size(); k++) {
                    ObjectFild ofild = fieldList.get(k);
                    //获取字段名字
                    String methodName = "get" + ofild.fieldName.substring(0, 1).toUpperCase() + ofild.fieldName.substring(1);
                    Method method = aClass1.getMethod(methodName);
                    Object value = method.invoke(aList);
                    //把获取到的值写入excel
                    row.createCell(k).setCellValue(value == null ? "" : value.toString());
                }
                j++;
            }
        }
        return wb;
    }

    static class ObjectFild {
        int order;
        String fieldName;
        Field field;
    }

    private static List<Field> getAllFields(Class clazz) {
        if (clazz == null) {
            throw new NullPointerException("对象不能为空");
        }
        List<Field> list = new ArrayList<Field>();
        Field[] declaredFields;
        do {
            //获取本身的所有字段
            declaredFields = clazz.getDeclaredFields();
            if (declaredFields!=null && declaredFields.length>0) {
                Collections.addAll(list, declaredFields);
            }
            clazz = clazz.getSuperclass();
        } while (clazz != null && declaredFields!=null && declaredFields.length>0);

        return list;
    }

}
